﻿using System;
using System.Configuration;
using System.IO;
using System.ServiceProcess;
using System.Threading;
using ThinkAway.IO.Log;

namespace ThinkAway.Plus.Office
{
    public partial class ProjectService : ServiceBase
    {
        private readonly ILog _logger;

        private readonly string _filter;
        private readonly string _outputPath;
        private readonly string _moniterPath;

        private readonly FileSystemWatcher _fileSystemWatcher;
        private readonly IOfficeFormatConvert _officeFormatConvert;

        public ProjectService()
        {
            InitializeComponent();

            _logger = new Logger {Config = {Mode = LogMode.Text}};

            _logger.Info("log","log start .");

            AppDomain.CurrentDomain.UnhandledException += (sender, obj) => _logger.Error("log", (Exception)obj.ExceptionObject);
            
            _filter = ConfigurationManager.AppSettings["Filter"];
            _outputPath = ConfigurationManager.AppSettings["OutputPath"];
            _moniterPath = ConfigurationManager.AppSettings["MoniterPath"];
            
            _officeFormatConvert = new OfficeFormatConvert();

            try
            {
                _fileSystemWatcher = new FileSystemWatcher(_moniterPath, _filter);
                _fileSystemWatcher.Created += FileSystemWatcherCreated;
                _logger.Debug("log", "MoniterPath:{0},Filter:{1},OutputPath:{2}.", _moniterPath, _filter, _outputPath);
            }
            catch (Exception exception)
            {
                _logger.Error("log",exception);
            }
        }

        void FileSystemWatcherCreated(object sender, FileSystemEventArgs e)
        {
            string inputFile = e.FullPath;
            string fileName = Path.GetFileNameWithoutExtension(e.Name) + ".pdf";
            string outputFile = Path.Combine(_outputPath, fileName);
            int errcode = _officeFormatConvert.Convert(new[] {inputFile}, new[] {outputFile});
            _logger.Debug("log","Convert:{0} to {1},Status:{2}",inputFile,outputFile,errcode);
        }

        public  void Start()
        {
            OnStart(new string[]{});
        }

        protected override void OnStart(string[] args)
        {
            Thread thread = new Thread(() =>
            {
                _fileSystemWatcher.EnableRaisingEvents = true;
                _fileSystemWatcher.WaitForChanged(WatcherChangeTypes.Created);
            });
            thread.Start();
            _logger.Debug("log","Service started .");
        }

        protected override void OnStop()
        {
            _fileSystemWatcher.EnableRaisingEvents = false;
            _logger.Debug("log", "Service stoped .");
        }
    }
}
